<template>
	<view class="container">
		<custom-status-bar></custom-status-bar>
		<!-- 顶部导航 -->
		<view class="header">
			<image src="/static/icon/luckin-logo.png" class="logo" />
			<text class="skip-btn" @click="skipToHome">先逛一逛</text>
		</view>
		<!-- 登录表单 -->
		<view class="form-container">
			<view class="welcome">欢迎回来!</view>
			<view class="login-tip">Please login to your accounts</view>
			<!-- 手机号输入 -->
			<view class="input-item">
				<text>手机号</text>
				<input v-model="phone" type="number" placeholder="手机号" class="input-field"
					@input="validatePhone(phone)" />
			</view>
			<!-- 密码输入 -->
			<view class="input-item password-section">
				<text>密码</text>
				<input v-model="password" :type="showPassword ? 'text' : 'password'" placeholder="密码必须为字母开头"
					class="input-field" @input="validatePassword(password)" />
				<uni-icons :type="showPassword ? 'eye' : 'eye-slash'" size="20" color="#999" @click="togglePassword" />
			</view>
			<!-- 验证提示 -->
			<view v-if="loginError" class="error">{{ loginError }}</view>
			<!-- 忘记密码 -->
			<view class="forgot-password" @click="handleForgot">忘记密码?</view>
			<!-- 登录按钮 -->
			<view class="login-btn" :disabled="!loginValid" @click="handleLogin">
				<text>登录</text>
			</view>
			<!-- 注册链接 -->
			<view class="register-link" @click="openToRegister">
				<text>注册</text>
			</view>
		</view>
		<!-- 注册表单 -->
		<uni-popup ref="popup" type="bottom">
			<view class="register-popup">
				<!-- 关闭按钮 -->
				<uni-icons type="closeempty" color="#999999" size="20" class="close-btn"
					@click="closeRegister"></uni-icons>
				<!-- 标题 -->
				<text class="title">注册</text>
				<!-- 表单内容 -->
				<view class="form-container">
					<!-- 手机号输入 -->
					<view class="input-item">
						<text>手机号</text>
						<input v-model="reg_phone" type="number" placeholder="11位手机号" class="input-field"
							@input="validateRegPhone(reg_phone)" />
					</view>
					<!-- 密码输入 -->
					<view class="input-item password-section">
						<text>密码</text>
						<input v-model="reg_password" :type="reg_showPassword ? 'text' : 'password'"
							placeholder="密码必须为字母开头" class="input-field" @input="validateRegPassword(reg_password)" />
						<uni-icons :type="reg_showPassword ? 'eye' : 'eye-slash'" size="20" color="#999"
							@click="reg_showPassword = !reg_showPassword" />
					</view>
					<!-- 昵称输入 -->
					<view class="input-item">
						<text>昵称</text>
						<input v-model="reg_nickname" placeholder="昵称" class="input-field"
							@input="validateRegNickname(reg_nickname)" />
					</view>
					<!-- 验证提示 -->
					<text v-if="reg_error" class="error">{{ reg_error }}</text>
					<!-- 注册按钮 -->
					<view class="register-btn" :disabled="!regValid" @click="handleRegister"> <text>注册</text></view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script setup>
	import CustomStatusBar from '../../components/common/CustomStatusBar.vue';
	import {
		login,
		register,
		accountInfo
	} from "@/api/index.js"
	import {
		ref
	} from 'vue';
	import {
		onShow
	} from "@dcloudio/uni-app"
	const phone = ref('');
	const password = ref('');
	const showPassword = ref(false);
	const loginError = ref('');
	const loginValid = ref(false);
	const reg_phone = ref('');
	const reg_password = ref('');
	const reg_showPassword = ref(false);
	const reg_nickname = ref('');
	const reg_error = ref('');
	const regValid = ref(false);
	const popup = ref();
	// 登录表单验证
	const validatePhone = (phoneVal) => {
		const regex = /^1[3-9]\d{9}$/;
		if (regex.test(phoneVal)) {
			loginError.value = '';
			checkLoginFormValidity();
		} else {
			loginError.value = '请输入有效的手机号';
		}
	};
	const validatePassword = (passwordVal) => {
		const regex = /^[A-Za-z].+/;
		// if (regex.test(passwordVal)) {
		if (true) {
			loginError.value = '';
			checkLoginFormValidity();
		} else {
			loginError.value = '密码必须以字母开头';
		}
	};
	const checkLoginFormValidity = () => {
		loginValid.value = !!phone.value && !!password.value && !loginError.value;
	};
	// 注册表单验证
	const validateRegPhone = (phoneVal) => {
		const regex = /^1[3-9]\d{9}$/;
		if (regex.test(phoneVal)) {
			reg_error.value = '';
			checkRegFormValidity();
		} else {
			reg_error.value = '请输入有效的手机号';
		}
	};
	const validateRegPassword = (passwordVal) => {
		const regex = /^[A-Za-z].+/;
		// if (regex.test(passwordVal)) {
		if (true) {
			reg_error.value = '';
			checkRegFormValidity();
		} else {
			reg_error.value = '密码必须以字母开头';
		}
	};
	const validateRegNickname = (nickVal) => {
		if (nickVal.trim().length >= 2) {
			reg_error.value = '';
			checkRegFormValidity();
		} else {
			reg_error.value = '请输入有效的昵称';
		}
	};
	const checkRegFormValidity = () => {
		regValid.value = !!reg_phone.value && !!reg_password.value && !!reg_nickname.value && !reg_error.value;
	};
	// 登录处理
	const handleLogin = async () => {
		if (!loginValid.value) {
			uni.showModal({
				title: '请输入正确的手机号和密码',
				showCancel: false
			})
			return;
		}
		uni.showLoading({title: '登录中...'});
		const response = await login(password.value, phone.value);
		console.log("登录：", response);
		if (response.code === 200) {
			uni.setStorageSync('coffee_token', response.token);
			// 发送全局事件通知购物车刷新
			// uni.$emit('loginSuccess')
			uni.hideLoading();
			uni.showToast({
				title: response.msg,
				icon: 'success',
				duration: 1000
			});	
				let pages = getCurrentPages()
				let previousPage = pages[pages.length - 2];
				if (previousPage && previousPage.route === 'pages/cart/cart') {
					uni.switchTab({
						url: '/pages/cart/cart'
					})
				} else if (previousPage && previousPage.route === 'pages/user/user') {
					uni.switchTab({
						url: '/pages/user/user'
					})
				} else  {
					uni.switchTab({
						url: '/pages/index/index'
					})
				}
				
				console.log("previousPage:",previousPage)
				
				// const userInfoRes = await accountInfo(response.token);
				// if (userInfoRes.code === 'B001') {
				// 	uni.setStorageSync('userInfo', JSON.stringify(userInfoRes.result[0]));
					
				// }
			
		} else {
			uni.showToast({
				title: response.msg,
				icon: 'error',
			});
		}
	};
	// 注册处理
	const handleRegister = async () => {
		validateRegPhone(reg_phone.value);
		validateRegPassword(reg_password.value);
		validateRegNickname(reg_nickname.value);
		if (!regValid.value) {
			uni.showModal({
				title: '请输入正确注册信息',
				showCancel: false
			})
			return;
		};
		try {
			const response = await register(reg_nickname.value, reg_password.value, reg_phone.value);
			console.log("注册:", response);
			if (response.code === 100) {
				uni.showToast({
					title: response.msg,
					icon: 'success',
					duration: 2000
				});
				// 注册成功，拿到token之后，再自动登录
				try {
					const res = await login(reg_password.value, reg_phone.value);
					if (res.code === 200) {
						uni.setStorageSync('coffee_token', res.token);
						uni.showToast({
							title: res.msg,
							icon: 'success',
							duration: 2000
						});
						// 获取用户信息并存储到本地
						try {
							const userInfoRes = await accountInfo(res.token);
							if (userInfoRes.code === 'B001') {
								uni.setStorageSync('userInfo', JSON.stringify(userInfoRes.result[0]));
							}
						} catch (userInfoError) {
							console.error("获取用户信息失败:", userInfoError);
						}
						uni.switchTab({
							url: '/pages/index/index'
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'error',
							duration: 2000
						});
					}
				} catch (e) {
					uni.showToast({
						title: e.message,
						icon: 'error',
						duration: 2000
					});
				}
				uni.switchTab({
					url: '/pages/index/index'
				});
			} else {
				uni.showToast({
					title: response.msg,
					icon: 'error',
					duration: 2000
				});
			}
		} catch (e) {
			uni.showToast({
				title: e.message,
				icon: 'error',
				duration: 2000
			});
		}
	};
	// 辅助方法
	const skipToHome = () => {
		uni.switchTab({
			url: '/pages/index/index'
		})
	};
	const handleForgot = () => {
		uni.showToast({
			title: '暂未开放此功能',
			icon: 'none'
		});
	};
	const openToRegister = () => {
		resetRegInput()
		popup.value.open();
	};
	const closeRegister = () => {
		popup.value.close();
	};
	const togglePassword = () => {
		showPassword.value = !showPassword.value;
	};
	const resetRegInput = () => {
		reg_nickname.value = ''
		reg_password.value = ''
		reg_phone.value = ''
		reg_showPassword.value = false
	}
	onShow(() => {
		// 用户已经登录就直接进入首页
		if (uni.getStorageSync('coffee_token')) {
			uni.switchTab({
				url: '/pages/index/index'
			})
		}
	})
</script>
<style scoped>
	.container {
		padding: 40rpx;
		background: white;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 80rpx;
	}

	.logo {
		width: 360rpx;
		height: 100rpx;
	}

	.skip-btn {
		color: #007AFF;
		font-size: 28rpx;
	}

	.welcome {
		font-size: 48rpx;
		font-weight: bold;
		margin-bottom: 40rpx;
	}

	.login-tip {
		color: #666;
		margin-bottom: 60rpx;
	}

	.input-item {
		display: flex;
		align-items: center;
		margin-bottom: 40rpx;
		border-bottom: 2rpx solid #eee;
	}

	.input-field {
		flex: 1;
		margin-left: 20rpx;
		padding: 20rpx 0;
	}

	.password-section {
		position: relative;
	}

	.eye-icon {
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
	}

	.error {
		color: red;
		font-size: 24rpx;
		margin-top: 10rpx;
		margin-bottom: 40rpx;
	}

	.forgot-password {
		color: #007AFF;
		text-align: right;
		margin-bottom: 60rpx;
	}

	.login-btn {
		display: block;
		text-align: center;
		background-color: #232773;
		border: 1rpx solid #232773;
		color: white;
		border-radius: 40rpx;
		padding: 20rpx 0;
		font-size: 32rpx;
		margin-bottom: 40rpx;
	}

	.register-link {
		display: block;
		text-align: center;
		color: #333;
		background-color: #ffffff;
		border-radius: 40rpx;
		padding: 20rpx 0;
		font-size: 32rpx;
		border: 1rpx solid #333333;
	}

	.register-popup {
		background-color: #ffffff;
		padding: 40rpx;
	}

	.register-popup .close-btn {
		float: right;
		font-size: 30rpx;
		cursor: pointer;
		margin-bottom: 20rpx;
	}

	.register-popup .title {
		font-size: 40rpx;
		font-weight: bold;
		margin-bottom: 40rpx;
	}

	.register-popup .form-container {
		margin-top: 40rpx;
	}

	.register-btn {
		display: block;
		text-align: center;
		background-color: #232773;
		border: 1rpx solid #232773;
		color: white;
		border-radius: 40rpx;
		padding: 20rpx 0;
		font-size: 32rpx;
		margin-top: 50rpx;
	}
</style>